package cn.yuanqiao.archive.yuguidang.service.impl;/**
 * @author 赵常飞
 * @date 2023/9/26 14:25
 */

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantMdataListMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqFolderMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqdaMapper;
import cn.yuanqiao.archive.yuguidang.domain.YuguidangArchiveForm;
import cn.yuanqiao.archive.yuguidang.mapper.yuguidangMapper;
import cn.yuanqiao.archive.yuguidang.service.IYuguidangService;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 *@AUTHOR:赵常飞
 *@date 2023/9/26 14:25
 */
@Service
public class yuguidangServiceImpl implements IYuguidangService {
    @Autowired
    private yuguidangMapper yuguidangMapper;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private TenantYqFolderMapper folderMapper;
    @Autowired
    private TenantYqdaMapper yqdaMapper;
    @Autowired
    private TenantMdataListMapper tenantMdataListMapper;

    @Override
    public boolean checkArchiveIsAddForm(List<YuguidangArchiveForm> yuguidangArchiveForms) {
        int i = yuguidangMapper.checkArchiveIsAddForm(yuguidangArchiveForms);
        return i==0?false:true;
    }

    @Override
    public boolean checkArchiveUserCategoryForm(List<YuguidangArchiveForm> yuguidangArchiveForms) {
        int i = yuguidangMapper.checkArchiveUserCategoryForm(yuguidangArchiveForms);
        return i==0?false:true;
    }

    @Override
    public Map<String, List<String>> getIdWhichHasData(String ids, String daType, Long categoryId) {
        Map<String, List<String>> map = new HashMap<>();   //项目类型 key:项目id value:案卷ids  案卷类型 key:案卷id value:卷内ids
        TenantCategory tenantCategory = new TenantCategory();
        TenantCategory category = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCategory.getTableName());
        String[] idsArr = ids.split(",");
        TenantItemFolder tenantItemFolder = new TenantItemFolder();
        TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
        for(int i=0;i<idsArr.length;i++){
            List<String> idsStr = new ArrayList<>();
            String id = idsArr[i];
            Long[] l = {Long.valueOf(id)};
            if("X".equals(daType)){
                Long[] folderIdsByItemIds = folderMapper.getFolderIdsByItemIds(l, category.getFolderTableName(), tenantItemFolder.getTableName());//查询项目下的卷
                if(!(folderIdsByItemIds== null || folderIdsByItemIds.length==0)){
                    for(int j=0;j<folderIdsByItemIds.length;j++){
                        Long folderIdsByItemId = folderIdsByItemIds[j];
                        Long[] l2 = {folderIdsByItemId};
                        Long[] daIdsByFolderIds = yqdaMapper.getDaIdsByFolderIds(l2, category.getFileTableName(), tenantYqdaFolder.getTableName());//查询卷下的件
                        if(!(daIdsByFolderIds== null || daIdsByFolderIds.length==0)){
                            idsStr.add(String.valueOf(folderIdsByItemId));
                        }

                    }
                }
            }
            if("V".equals(daType)){
                Long[] daIdsByFolderIds = yqdaMapper.getDaIdsByFolderIds(l, category.getFileTableName(), tenantYqdaFolder.getTableName());//查询卷下的件
                if(!(daIdsByFolderIds== null || daIdsByFolderIds.length==0)){
                    for(int i1 = 0;i1<daIdsByFolderIds.length;i1++){
                        idsStr.add(String.valueOf(daIdsByFolderIds[i1]));
                    }
                }
            }
            if(idsStr.size()!=0){
                map.put(id,idsStr);
            }
        }
        return map;
    }

    @Override
    public int batchInsertYqdaArchiveForm(List<YuguidangArchiveForm> yuguidangArchiveForms) {
        return yuguidangMapper.batchInsertYqdaArchiveForm(yuguidangArchiveForms);
    }

    @Override
    public int updateYqArchiveState(List<YuguidangArchiveForm> yuguidangArchiveForms, int state) {
        Long categoryId = yuguidangArchiveForms.get(0).getCategoryId();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        int i = 0;
        for (YuguidangArchiveForm item : yuguidangArchiveForms) {
            String archiveId = item.getArchiveId();
            Integer type = tenantCategory.getType();
            if (type == 0){
                String fileTableName = tenantCategory.getFileTableName();
                StringBuilder sqlBulider = new StringBuilder();
                sqlBulider.append("UPDATE ").append(tenantCode).append("_YQDA SET STATE = ").append(state).append(" WHERE DA_ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(fileTableName).append(" SET STATE = ").append(state).append(" WHERE ID = ").append(item.getArchiveId());
                yuguidangMapper.updateArchiveBySaveFormArchiveId(sqlBulider.toString());
            }else if (type == 1){
                String fileTableName = tenantCategory.getFileTableName();
                String folderTableName = tenantCategory.getFolderTableName();
                StringBuilder sqlBulider = new StringBuilder();
                sqlBulider.append("UPDATE ").append(tenantCode).append("_YQFOLDER SET STATE = ").append(state).append(" WHERE FOLDER_ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(folderTableName).append(" SET STATE = ").append(state).append(" WHERE ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(tenantCode).append("_YQDA SET STATE = ").append(state).append(" WHERE DA_ID IN (SELECT DA_ID FROM ").append(tenantCode)
                        .append("_YQDA_FOLDER WHERE FOLDER_ID = ").append(item.getArchiveId()).append(")")
                        .append(";UPDATE ").append(fileTableName).append(" SET STATE = ").append(state).append(" WHERE ID IN (SELECT DA_ID FROM ").append(tenantCode)
                        .append("_YQDA_FOLDER WHERE FOLDER_ID = ").append(item.getArchiveId()).append(")");
                yuguidangMapper.updateArchiveBySaveFormArchiveId(sqlBulider.toString());
            }else if (type == 3){
                String fileTableName = tenantCategory.getFileTableName();
                String folderTableName = tenantCategory.getFolderTableName();
                String itemTableName = tenantCategory.getItemTableName();
                StringBuilder sqlBulider = new StringBuilder();
                sqlBulider.append("UPDATE ").append(tenantCode).append("_YQITEM SET STATE = ").append(state).append(" WHERE ITEM_ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(itemTableName).append(" SET STATE = ").append(state).append(" WHERE ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(tenantCode).append("_YQFOLDER SET STATE = ").append(state).append(" WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM ").append(tenantCode)
                        .append("_ITEM_FOLDER WHERE ITEM_ID = ").append(item.getArchiveId()).append(")")
                        .append(";UPDATE ").append(folderTableName).append(" SET STATE = ").append(state).append(" WHERE ID IN (SELECT FOLDER_ID FROM  ").append(tenantCode)
                        .append("_ITEM_FOLDER WHERE ITEM_ID = ").append(item.getArchiveId()).append(")")
                        .append(";UPDATE ").append(tenantCode).append("_YQDA SET STATE = ").append(state).append(" WHERE DA_ID IN (SELECT DA_ID FROM ").append(tenantCode)
                        .append("_YQDA_FOLDER WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM ").append(tenantCode).append("_ITEM_FOLDER WHERE ITEM_ID = ")
                        .append(item.getArchiveId()).append("))")
                        .append(";UPDATE ").append(fileTableName).append(" SET STATE = ").append(state).append(" WHERE ID IN (SELECT DA_ID FROM  ").append(tenantCode)
                        .append("_YQDA_FOLDER WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM ").append(tenantCode).append("_ITEM_FOLDER WHERE ITEM_ID = ")
                        .append(item.getArchiveId()).append("))");
                yuguidangMapper.updateArchiveBySaveFormArchiveId(sqlBulider.toString());
            }

        }
        return i;
    }

    @Override
    public YuguidangArchiveForm selectYqdaArchiveFormByFormId(Long formId) {
        return yuguidangMapper.selectYqdaArchiveFormByFormId(new YuguidangArchiveForm().getTableName(),formId);
    }

    @Override
    public List<Map<String, Object>> getArchiveInfo(YuguidangArchiveForm yuguidangArchiveForm, String commonCloumns, String level) {
        commonCloumns = "*,";//FIXME 警告：测试用，正式环境需要删除此代码
        Long categoryId = yuguidangArchiveForm.getCategoryId();
        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        Integer type = tenantCategory.getType();
        String tableName = null;
        if ("jian".equals(level.toLowerCase())){
            tableName = tenantCategory.getFileTableName();
        }else if ("juan".equals(level.toLowerCase())){
            tableName = tenantCategory.getFolderTableName();
        }else if ("xiangmu".equals(level.toLowerCase())){
            tableName = tenantCategory.getItemTableName();
        }else if ("efile".equals(level.toLowerCase())){
            tableName = tenantCategory.getEfileTableName();
        }
        if ((type ==0&&"jian".equals(level.toLowerCase()))||(type ==1&&"juan".equals(level.toLowerCase()))||(type ==3&&"xiangmu".equals(level.toLowerCase()))){
            sqlBulider.append("SELECT ").append(commonCloumns).append(categoryId).append(" AS CATEGORY_ID,'").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName)
                    .append(" WHERE ID IN(").append(yuguidangArchiveForm.getArchiveId()).append(") AND IS_DEL = 0");
        }else if ((type ==1&&"jian".equals(level.toLowerCase()))||(type ==3&&"jian".equals(level.toLowerCase()))){
            sqlBulider.append(" SELECT ").append(commonCloumns).append(categoryId).append(" AS CATEGORY_ID,'").append(tableName).append("' AS SUB_TABLE_NAME  FROM ").append(tableName)
                    .append("  WHERE ID IN( SELECT DA_ID FROM ").append(tenantCode).append("_YQDA_FOLDER WHERE FOLDER_ID =")
                    .append(yuguidangArchiveForm.getArchiveId()).append(") AND IS_DEL = 0");
        }else if (type ==3&&"juan".equals(level.toLowerCase())){
            sqlBulider.append(" SELECT ").append(commonCloumns).append(categoryId).append(" AS CATEGORY_ID,'").append(tableName).append("' AS SUB_TABLE_NAME  FROM  ").append(tableName)
                    .append("  WHERE ID IN(SELECT FOLDER_ID FROM ").append(tenantCode).append("_ITEM_FOLDER WHERE ITEM_ID =").append(yuguidangArchiveForm.getArchiveId()).append(") AND IS_DEL = 0");
        }else {
            throw new RuntimeException("档案类型daType不能为空");
        }
        return yuguidangMapper.selectYqdaArchiveList(sqlBulider.toString());
    }

    @Override
    public int updateYqdaArchiveForm(YuguidangArchiveForm yuguidangArchiveForm) {
        return yuguidangMapper.updateYqdaArchiveForm(yuguidangArchiveForm);
    }

    @Override
    public List<YuguidangArchiveForm> selectYqdaArchiveFormsByArchiveIds(String[] archiveIds) {
        return yuguidangMapper.selectYqdaArchiveFormsByArchiveIds(archiveIds,SecurityUtils.getUserId(),new YuguidangArchiveForm().getTableName());
    }

    @Override
    public int deleteYqdaArchiveFormByArchiveIdsAndUserId(String[] archiveIds, Long userId) {
        return yuguidangMapper.deleteYqdaArchiveFormByArchiveIdsAndUserId(archiveIds,userId,new YuguidangArchiveForm().getTableName());
    }

    @Override
    public List<Map<String, Object>> getArchiveListByArchiveCategory(YuguidangArchiveForm yuguidangArchiveForm) {
        yuguidangArchiveForm.setState("0");
        yuguidangArchiveForm.setUserId(String.valueOf(SecurityUtils.getUserId()));
        List<YuguidangArchiveForm> yuguidangArchiveForms = selectYqdaArchiveFormList(yuguidangArchiveForm);
        if (yuguidangArchiveForms.size()==0){
            return null;
        }
        YuguidangArchiveForm tempData = yuguidangArchiveForms.get(0);
        Long categoryId = Long.valueOf(tempData.getCategoryIdaf());
        String daType = tempData.getDaType().toUpperCase();
        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        Integer type = tenantCategory.getType();
        String tableName = null;
        if (type==0){
            tableName = tenantCategory.getFileTableName();
        }else if (type==1){
            tableName = tenantCategory.getFolderTableName();
        }else if (type==3){
            tableName = tenantCategory.getItemTableName();
        }

        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setIsHidden(0);
        List<TenantMdataList> tenantMdataLists = tenantMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList, categoryId, tenantCode + "_CATEGORY");

        StringBuilder fieldCommon = new StringBuilder();
        StringBuilder archiveIdBuilder = new StringBuilder();
        yuguidangArchiveForms.forEach(item->archiveIdBuilder.append(item.getArchiveId()).append(","));
        //FIXME 测试用字段
        //tenantMdataLists.forEach(item->fieldCommon.append(item.getFieldName()).append(","));
        fieldCommon.append("*,");

        archiveIdBuilder.deleteCharAt(archiveIdBuilder.length()-1);
        String archiveIds = archiveIdBuilder.toString();
        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        sqlBulider.append("SELECT ").append(fieldCommon).append(categoryId).append(" AS CATEGORY_ID,'").append(daType)
                .append("' AS DA_TYPE, '").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName).append(" WHERE ID IN(").append(archiveIds).append(") AND IS_DEL = 0");
        return yuguidangMapper.selectYqdaArchiveList(sqlBulider.toString());
    }

    @Override
    public List<YuguidangArchiveForm> selectYqdaArchiveFormList(YuguidangArchiveForm yuguidangArchiveForm)
    {
        return yuguidangMapper.selectYqdaArchiveFormList(yuguidangArchiveForm);
    }

    @Override
    public List<Map<String, Object>> getArchiveListByArchiveFormList(List<YuguidangArchiveForm> yuguidangArchiveForms) {
        YuguidangArchiveForm tempData = yuguidangArchiveForms.get(0);
        Long categoryId = Long.valueOf(tempData.getCategoryIdaf());
        String daType = tempData.getDaType().toUpperCase();
        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        Integer type = tenantCategory.getType();
        String tableName = null;
        if (type==0){
            tableName = tenantCategory.getFileTableName();
        }else if (type==1){
            tableName = tenantCategory.getFolderTableName();
        }else if (type==3){
            tableName = tenantCategory.getItemTableName();
        }

        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setIsHidden(0);
        List<TenantMdataList> tenantMdataLists = tenantMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList, categoryId, tenantCode + "_CATEGORY");

        StringBuilder fieldCommon = new StringBuilder();
        StringBuilder archiveIdBuilder = new StringBuilder();
        yuguidangArchiveForms.forEach(item->archiveIdBuilder.append(item.getArchiveId()).append(","));
        //FIXME 需要解开的注释
        //tenantMdataLists.forEach(item->fieldCommon.append(item.getFieldName()).append(","));

        archiveIdBuilder.deleteCharAt(archiveIdBuilder.length()-1);
        String archiveIds = archiveIdBuilder.toString();
        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        //FIXME 测试流程用数据，字段用* 代替，记得删除
        fieldCommon.append("*,");
        sqlBulider.append("SELECT ").append(fieldCommon).append(categoryId).append(" AS CATEGORY_ID,'").append(daType)
                .append("' AS DA_TYPE, '").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName).append(" WHERE ID IN(").append(archiveIds).append(") AND IS_DEL = 0");
        return yuguidangMapper.selectYqdaArchiveList(sqlBulider.toString());
    }

    @Override
    public int batchUpdateByArchiveIds(YuguidangArchiveForm yuguidangArchiveForm) {
        return yuguidangMapper.batchUpdateByArchiveIds(yuguidangArchiveForm);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int tuihui(JSONObject json) {
        String ids=json.getString("ids");
        Long categoryId=json.getLong("categoryId");
        try {
            TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, new TenantCategory().getTableName());
            if ("0".equals(String.valueOf(tenantCategory.getType()))) {//件
                yuguidangMapper.tuihui(new TenantYqda().getTableName(),"DA_ID", tenantCategory.getFileTableName(), ids);
            } else if ("1".equals(String.valueOf(tenantCategory.getType()))) {//卷
                yuguidangMapper.tuihui(new TenantYqFolder().getTableName(),"FOLDER_ID", tenantCategory.getFolderTableName(), ids);
                String jianidsql = "select da_id from " + new TenantYqdaFolder().getTableName() + " where folder_id in(" + ids + ")";//处理件
                yuguidangMapper.tuihui(new TenantYqda().getTableName(),"DA_ID", tenantCategory.getFileTableName(), jianidsql);
            } else if ("3".equals(String.valueOf(tenantCategory.getType()))) {//项目
                yuguidangMapper.tuihui(new TenantYqItem().getTableName(),"ITEM_ID", tenantCategory.getItemTableName(), ids);
                String juansql = "select folder_id from " + new TenantItemFolder().getTableName() + " where item_id in(" + ids + ")";//处理卷
                yuguidangMapper.tuihui(new TenantYqFolder().getTableName(),"FOLDER_ID", tenantCategory.getFolderTableName(), juansql);
                String jiansql = "select da_id from " + new TenantYqdaFolder().getTableName() + " where folder_id in(" + juansql + ")";//处理件
                yuguidangMapper.tuihui(new TenantYqda().getTableName(),"DA_ID", tenantCategory.getFileTableName(), jiansql);
            }
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
